Source code for /engineering/webperf/master-v2[j1.2]/CGI.javaOriginal file CGI.java
   1 import java.net.*;
   2 import java.io.*;
   3 import java.util.*;
   4 
   5 /**
   6 CGIStuff is a class that holds methods useful to anyone writing a CGI back-end in Java.
   7 It's supplied as part of the JavaCGI package.
   8 @author Ben Last (ben@hypereality.co.uk)
   9 @version 1.0, 4/7/96
  10 */
  11 
  12 public class CGI
  13 {
  14    //full of class methods, really.
  15 
  16    /**
  17       Split a QUERY_STRING (or the contents of stdin for a POST) into a HashTable.
  18       The method doesn't expect <VAR>queryString</VAR> to have been urlDecoded.  It will
  19       decode all the variables and names.
  20    */
  21    public static Hashtable splitVars(String queryString)
  22    {
  23       return splitCodedVars(queryString, true);
  24    }
  25    
  26    protected static Hashtable splitCodedVars(String queryString, boolean decode)
  27    {
  28    Hashtable   vars = new Hashtable();
  29    String      name = null;
  30    boolean     asName = true;
  31    
  32       //We mustn't decode the string yet because that might introduce more '&' characters
  33       //which we don't want.
  34 
  35       //split at every '&' or '=' into substrings.  We need also to handle the
  36       //fact that the final variable doesn't end in an '&'.
  37       StringTokenizer st = new StringTokenizer(queryString, "&=", true);
  38       while(st.hasMoreTokens())
  39       {
  40          String var = st.nextToken();
  41          //if we've been returned an '=' or an '&', that tells us
  42          //what the next token should be treated as.
  43          if(var.equals("="))
  44          {
  45             asName = false;   //next token is a value
  46             continue;
  47          }
  48 
  49          if(var.equals("&"))
  50          {
  51             //we may have a name, but no value, in which case we add it as an
  52             //empty property.
  53             if(name != null)
  54             {
  55                vars.put(name,"");
  56                name = null;
  57             }
  58             asName = true; //next token is a name
  59             continue;
  60          }
  61 
  62          if(asName)
  63          {
  64             name = decode ? URLDecoder.decode(var) : var;
  65             continue;
  66          }
  67 
  68          //we have a value.  If we also have a name, then add as a property.
  69          if(name != null)
  70          {
  71             vars.put(name, decode ? URLDecoder.decode(var) : var);
  72             name = null;
  73          }
  74       }
  75 
  76       //if name is not null here, we had a trailing empty valueless variable.
  77       if(name != null)
  78          vars.put(name,"");
  79 
  80       return vars;
  81    }
  82    
  83    public static String joinHashtableVars(Hashtable vars) {
  84       boolean first = true;
  85       String key, value;
  86       String ret = "";
  87                   
  88       for (Enumeration keys = vars.keys(); keys.hasMoreElements(); first = false) {
  89          key = (String) keys.nextElement();
  90 
  91          if (!first) {
  92             ret += "&";
  93          }
  94          ret += URLEncoder.encode(key) + "=" + URLEncoder.encode((String) vars.get(key));
  95       }
  96       
  97       return ret;
  98    }
  99  
 100    public static String post(URL url, Hashtable headers, Hashtable data) throws IOException {
 101       String content, line, response, key;    
 102       HttpURLConnection connection;
 103       DataInputStream in;
 104       DataOutputStream out;
 105       int responseCode;
 106             
 107       // Create the URL and its connection
 108       connection = (HttpURLConnection) url.openConnection();
 109       
 110       // Setup our connection state    
 111       connection.setRequestMethod("POST");
 112       connection.setDoInput(true);
 113       connection.setDoOutput(true);    
 114       connection.setUseCaches(false);
 115     
 116       // Build the content string from the hashtable
 117       content = CGI.joinHashtableVars(data);
 118          
 119       // We want to do a post operation
 120       connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
 121       connection.setRequestProperty("Content-length", new Integer(content.length()).toString());
 122 
 123       for (Enumeration keys = headers.keys(); keys.hasMoreElements(); ) {
 124          key = (String) keys.nextElement();
 125          connection.setRequestProperty(key, (String) headers.get(key));
 126       }
 127      
 128       // Get an input and output stream for sending/receiving data
 129       out = new DataOutputStream(connection.getOutputStream());
 130 
 131       System.out.print("Sending message...");
 132       // Send the data and close the output stream
 133       out.writeBytes(content);
 134       out.flush();
 135       out.close();      
 136       System.out.println("done.");             
 137  
 138       // Read the server response    
 139       response = "";
 140       responseCode = connection.getResponseCode();
 141       if (responseCode != 200) {
 142          IOException e = new IOException("Server Error: " + responseCode + " " + connection.getResponseMessage());
 143          throw(e);
 144       }         
 145       in = new DataInputStream(connection.getInputStream()); 
 146       while ((line = in.readLine()) != null) {
 147          response += line + "\n";
 148       }    
 149  
 150       in.close();
 151       System.out.println("Message sent.");
 152       
 153       return response;
 154    }
 155         
 156 }